import { defineStore } from 'pinia'

export const usePlayerStore = defineStore('player', {
  state: () => ({
    // 当前播放的歌曲
    currentSong: {
      id: null,
      name: '',
      singerName: '',
      url: '',
      picUrl: '',
      lyrics: '',
      duration: 0
    },

    // 播放状态
    isPlaying: false,

    // 当前播放时间
    currentTime: 0,

    // 音量 (0-1)
    volume: 0.7,

    // 播放列表
    playlist: [],

    // 当前播放索引
    currentIndex: -1,

    playMode: 'sequence'
  }),

  getters: {
    // 获取当前歌曲
    getCurrentSong: (state) => state.currentSong,

    // 获取播放状态
    getPlayingStatus: (state) => state.isPlaying,

    // 获取当前播放时间
    getCurrentTime: (state) => state.currentTime,

    // 获取音量
    getVolume: (state) => state.volume,

    // 获取播放列表
    getPlaylist: (state) => state.playlist,

    // 获取播放模式
    getPlayMode: (state) => state.playMode,

    // 获取下一首歌曲
    getNextSong: (state) => {
      if (state.playlist.length === 0) return null

      let nextIndex
      switch (state.playMode) {
        case 'random':
          // 随机播放（不重复当前歌曲）
          do {
            nextIndex = Math.floor(Math.random() * state.playlist.length)
          } while (nextIndex === state.currentIndex && state.playlist.length > 1)
          break
        case 'single':
          // 单曲循环
          nextIndex = state.currentIndex
          break
        default:
          // 顺序播放
          nextIndex = (state.currentIndex + 1) % state.playlist.length
      }

      return state.playlist[nextIndex] || null
    },

    // 获取上一首歌曲
    getPrevSong: (state) => {
      if (state.playlist.length === 0) return null

      let prevIndex
      switch (state.playMode) {
        case 'random':
          // 随机播放（不重复当前歌曲）
          do {
            prevIndex = Math.floor(Math.random() * state.playlist.length)
          } while (prevIndex === state.currentIndex && state.playlist.length > 1)
          break
        case 'single':
          // 单曲循环
          prevIndex = state.currentIndex
          break
        default:
          // 顺序播放
          prevIndex = (state.currentIndex - 1 + state.playlist.length) % state.playlist.length
      }

      return state.playlist[prevIndex] || null
    }
  },

  actions: {
    /**
     * 设置当前歌曲
     * @param {Object} song - 歌曲对象
     */
    setCurrentSong(song) {
        this.currentSong = {
            id: song.id || song.songId || null,
            name: song.name || song.songName || '',
            singerName: song.singerName || '',
            url: song.url || song.songUrl || '',
            picUrl: song.picUrl || song.songPic || '',
            songLyr: song.songLyr || song.lyrics || '',
            duration: song.duration || 0
        }

        // 在播放列表中查找该歌曲的索引
        const index = this.playlist.findIndex(item => item.id === (song.id || song.songId))
        if (index !== -1) {
            this.currentIndex = index
        }
    },

    /**
     * 设置播放状态
     * @param {boolean} status - 播放状态
     */
    setPlayingStatus(status) {
      this.isPlaying = status
    },

    /**
     * 设置当前播放时间
     * @param {number} time - 播放时间（秒）
     */
    setCurrentTime(time) {
      this.currentTime = time
    },

    /**
     * 设置音量
     * @param {number} volume - 音量值（0-1）
     */
    setVolume(volume) {
      this.volume = Math.max(0, Math.min(1, volume))
    },

    /**
     * 设置播放列表
     * @param {Array} playlist - 歌曲列表
     */
    setPlaylist(playlist) {
      this.playlist = [...playlist]
    },

    /**
     * 添加歌曲到播放列表
     * @param {Object|Array} songs - 歌曲对象或歌曲数组
     */
    addToPlaylist(songs) {
      const songArray = Array.isArray(songs) ? songs : [songs]
      this.playlist.push(...songArray)
    },

    /**
     * 从播放列表中移除歌曲
     * @param {number} songId - 歌曲ID
     */
    removeFromPlaylist(songId) {
      const index = this.playlist.findIndex(song => song.id === songId)
      if (index !== -1) {
        this.playlist.splice(index, 1)

        // 如果删除的是当前播放的歌曲或之前的歌曲，需要调整当前索引
        if (index < this.currentIndex) {
          this.currentIndex--
        } else if (index === this.currentIndex) {
          // 如果删除的是当前播放的歌曲，停止播放
          this.currentIndex = -1
          this.currentSong = this.$state.currentSong
          this.isPlaying = false
        }
      }
    },

    /**
     * 清空播放列表
     */
    clearPlaylist() {
      this.playlist = []
      this.currentIndex = -1
      this.currentSong = this.$state.currentSong
      this.isPlaying = false
    },

    /**
     * 设置播放模式
     * @param {string} mode - 播放模式
     */
    setPlayMode(mode) {
      const validModes = ['sequence', 'random', 'single']
      if (validModes.includes(mode)) {
        this.playMode = mode
      }
    },

    /**
     * 播放下一首
     */
    playNext() {
      if (this.playlist.length === 0) return

      const nextSong = this.getNextSong
      if (nextSong) {
        this.setCurrentSong(nextSong)
        this.isPlaying = true
      }
    },

    /**
     * 播放上一首
     */
    playPrev() {
      if (this.playlist.length === 0) return

      const prevSong = this.getPrevSong
      if (prevSong) {
        this.setCurrentSong(prevSong)
        this.isPlaying = true
      }
    },

    /**
     * 播放指定索引的歌曲
     * @param {number} index - 歌曲索引
     */
    playByIndex(index) {
      if (index >= 0 && index < this.playlist.length) {
        this.currentIndex = index
        this.setCurrentSong(this.playlist[index])
        this.isPlaying = true
      }
    }
  }
})
